<?php

namespace App\Http\Middleware;

use App\Models\Sites;
use Closure;

class Apitoken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $return = ['status' => false];
        $token = $request->wordsapi_token;
        if (!$token) {
            $return['msg'] = 'token missing!';
            return response($return);
        } else {
            $token = explode("_", $token);
            if (!is_array($token) || count($token) != 2) {
                $return['msg'] = 'token error!';
                return response($return);
            } else {
                //查找站点
                $record = Sites::where('url', $token[1])->first();
                if ($record) {
                    $pwd = md5($record['url']);
                    //验证token
                    if ($pwd != $token[0]) {
                        $return['msg'] = 'token加密不正确!';
                        return response($return);
                    }
                } else {
                    $return['msg'] = 'site missing!';
                    return response($return);
                }
            }
        }
        session(['site' => $record], 3000);
        return $next($request);
    }
}
